<?php
/**
 * 周舟 hzboye010@163.com
 * addby sublime snippets
 */
namespace Common\Api;

use Common\Api\Api;
use Admin\Model\GameModel;
use Common\Api\GamePrizegethisApi;
use Common\Api\GamePrizeApi;
use Admin\Api\MemberApi;
use Webview\Api\SigninApi;
use Shop\Api\RedEnvelopeApi;
use Common\Api\GameLogApi;
// use Shop\Api\ShoppingCartApi;
// use Admin\Model\GamePrizeModel;
// use Admin\Model\GamePrizegethisModel;

class GameApi extends Api
{
    //初始化
    protected function _init(){
        $this -> model  = new GameModel();
        // $this -> his = new GamePrizegethisModel();
    }
    const MAX_FREE     = 2; //每天签到送免费次数，不累计
    const MAX_CHANGES  = 5; //每天可抽次数上限
    const SCOREPREROLL = 10;//每次积分抽奖消耗
    const ROLL         = "Common/Game/roll";
    const FIND         = "Common/Game/getInfo";
    const CHECK        = "Common/Game/preRoll";
    const SAVE         = "Common/Game/save";
    const SAVEBYID     = "Common/Game/saveByID";
    const ADD          = "Common/Game/add";
    const DEL          = "Common/Game/delete";
    const PAGE         = "Common/Game/query";
    const CATS         = "Common/Game/getPrizeCats";
    const TEST         = "Common/Game/test";
    /**
     * 一次抽奖
     * @param  int      the user id
     * @param  int      the game id
     * @return array    results
     */
    public function  roll($uid,$gid){
        $maxFree      = self::MAX_FREE;
        $maxChange    = self::MAX_CHANGES;
        $free         = fasle;
        $scorePreRoll = self::SCOREPREROLL;
        $r = $this->preRoll($uid,$gid);
        if($r['status'])
        {
            $freeC    = intval($r['info']['remainF']);
            $score    = intval($r['info']['score']);
            $allC     = intval($r['info']['remainA']);
            $signin   = $r['info']['signin'];
            $gameName = $r['info']['game_name'];
            $status   = true;
            $this -> model -> startTrans();
            $msg    = '';
            $s      = $this->doRoll($gid);
            if($s['status'])
            {
                $pid = intval($s['info']['prize_id']);
                if($pid){
                    $result = apiCall(GamePrizeApi::FIND,array(array('id'=>$pid)));
                    if($result['status'])
                    {
                        $num   = intval($result['info']['prize_cnt']);
                        $pname = $result['info']['prize_name'];
                    }else{
                        return array('status'=>false,'info'=>'系统错误：get pri err！');
                    }
                    $result = apiCall(GamePrizegethisApi::COUNT,array(array('prize_id'=>$pid)));
                    if($result['status']){
                        if($num && $num < intval($result['info'])){
                            return array('status'=>false,'info'=>'对不起，'.$pname.'已抽完，本次抽奖无消耗！');
                        }
                    }else{
                        return array('status'=>false,'info'=>'系统错误：get his err！');
                    }
                }
                $r['info'] = $s['info'];
                $type   = intval($s['info']['prize_type']);
                $name   = $s['info']['prize_name'];
                $msgbox = array();
                $pid    = intval($s['info']['prize_id']);
                $num    = intval($s['info']['prize_num']);
                $allC  -=1;
                if($freeC>0)
                {
                    $type   = 0;//免费抽奖
                    $pid    = 0;
                    $freeC -= 1;
                }else{
                    //10积分抽奖
                    $result = apiCall(MemberApi::GET_INFO,array(array('uid'=>$uid)));
                    if(intval($result['info']['score']) < self::SCOREPREROLL){
                        return array('status'=>false,'info'=>'对不起，积分不足！');
                    }
                    $result = apiCall(MemberApi::SET_DEC,array(array('uid'=>$uid),'score',$scorePreRoll));
                    // dump($result);exit;
                    if($result['status'])
                    {
                        $score     -= $scorePreRoll;
                        $r['info']  = $s['info'];
                        // $r['info']['signin'] = false;
                    }else{
                        $status = false;
                        $msg    = 'Member-Score:ERROR';
                    }
                }
                //记录本次抽奖
                $map = array(
                    'prize_id'                =>$pid
                    ,'game_id'                =>$gid
                    ,'uid'                    =>$uid
                    ,'get_time'               =>NOW_TIME
                    ,'prize_type'             =>$type
                    ,'itboye_getprize_hiscol' =>'在['.$gameName.']中['.$name.']'
                );
                $result = apiCall(GamePrizegethisApi::ADD,array($map));
                if(!$result['status'])
                {
                    $status = false;
                    $msg    ='Prize+Record:ERROR';
                }
                //奖品发放
                //1积分：  score[int|the-score-number]
                //2购物券：redev[int|the-redev-number]
                //3商品：  goods[int|the-goods-id]
                //4其他：  other[int|you like]
                if(1 === $type)
                {
                    //add $num score to user[$uid]
                    $result = apiCall(MemberApi::SET_INC,array(array('uid'=>$uid),'score',$num));
                    // dump($result);exit;
                    if(!$result['status']){
                        $status = false;
                        $msg = '积分发放失败';
                    }
                    $score += $num;
                    $msgbox['title']   = '恭喜您抽中了'.$num.'积分';
                    $msgbox['content'] = '恭喜您在抽奖 - '.$gameName.' 中抽中了'.$name.',您获得了'.$num.'积分,请注意查看！';
                }elseif(3 === $type){
//TODO //添加购物车
                    $msgbox['title']   = '恭喜您抽中了编号为'.$num.'的商品';
                    $msgbox['content'] = '恭喜您在抽奖 - '.$gameName.' 中抽中了编号为'.$name.',您将获得编号为'.$num.'的商品,活动结束后工作人员会主动联系您，请保持通信畅通！';
                    //add goods $num to user[$uid]'s shopping cat
                    // $e          = array();
                    // $e['uid']   = $uid;
                    // $e['p_id']  = $num;
                    // $e['count'] = 1;
                    // $e['price'] = 0.1;
                    // $result     = apiCall(ShoppingCartApi::ADD,array($e));
                    // if(!$result['status']){
                    //     $status = false;
                    //     $msg = '商品发放失败';
                    // }
                }elseif(4 === $type){
                    $msgbox['title']   = '恭喜您抽中了编号为'.$num.'的实物';
                    $msgbox['content'] = '您的运气太好了,恭喜您在抽奖 - '.$gameName.'中抽中了实物大奖：'.$name.',活动结束后工作人员会主动联系您，请保持通信畅通！';
                }elseif(2 === $type){
                    $msgbox['title']   = '恭喜您抽中了'.$num.'元购物券';
                    $msgbox['content'] = '恭喜您在抽奖 - '.$gameName.' 中抽中了'.$name.',您获得了'.$num.'元购物券,请注意查看！';
                    //add $num red-envelope to user[$uid]
                    $e                = array();
                    $e['uid']         = $uid;
                    $e['get_time']    = NOW_TIME;
                    $e['money']       = $num;
                    $e['use_status']  = 0;
                    $e['tpl_id']      = 9; //无门槛
                    $e['expire_time'] = 86400*30; //30天 //购物券【奖品发放】
                    $e['notes']       = '中奖购物券'.$num.'元';
                    $result           = apiCall(RedEnvelopeApi::ADD,array($e));
                    if(!$result['status']){
                        $status = false;
                        $msg    = '购物券发放失败';
                    }
                }
                //发送中奖消息  6055=> gameMsg
                $map = array(
                    'uid'      =>$uid
                    ,'summary' =>$msgbox['title']
                    ,'content' =>$msgbox['content']
                );
                unset($msgbox);
                if($type){
                    $result = apiCall(GameLogApi::ADD,array($map));
                    // dump($result);exit;
                    if(!$result['status']){
                        $status = false;
                        $msg    ='MESSAGE+SEND:ERROR';
                    }
                }
                $r['info']['score']   = $score ;
                $r['info']['signin']  = $signin ;
                $r['info']['remainF'] = $freeC ;
                $r['info']['remainA'] = $allC ;
            }else{
                $status   = false;
                $r['info'] = $s['msg'];
            }
            // dump($r);exit;
            if($status){
                // $r['msg']  = 'commit ';
                $this->model->commit();
            }else{
                $r['status'] = false;
                $r['msg']    = 'rollback ';
                $r['info']   = $msg;
                $this->model->rollback();
            }
        }else{
            $status   = false;
            $r['info'] = $s['msg'];
        }
        return $r;
    }
    // public function test($uid,$pid){

    // }
    /**
     * 抽奖前检查
     * @param  [type] $uid [description]
     * @param  [type] $gid [description]
     * @return [arr]      [description]
     */
    public function preRoll($uid,$gid){
        // echo '2323';exit;
        $maxFree   = self::MAX_FREE;
        $maxChange = self::MAX_CHANGES;
        $r         = array('status'=>false,'info'=>array('signin'=>false,'remainF'=>0,'remainA'=>0),'msg'=>'');

        $result = apiCall(MemberApi::GET_INFO,array(array('uid'=>$uid)));
        // dump($result);exit;
        if(!$result['status'] || !$result['info']){
            $r['msg'] = '非法用户';
            return $r;
            // $r['msg'] = 'MemberApi:find:ERROR';
        }
//查询抽奖信息
        $result = $this->getInfo(array('id' => $gid));
        if(!$result['info']){
            $r['msg'] = '无此抽奖';
            return $r;
        }
        if( (NOW_TIME < $result['info']['start_time']) || (NOW_TIME > $result['info']['end_time']) ){
            $r['msg'] = '抽奖已失效';
            return $r;
        }
        $time0    = strtotime(Date('Y-m-d',NOW_TIME));
        $time1    = $time0 + 3600*24;
        $bettoday = array('between',array($time0,$time1));
//查询今天已抽奖次数
        $map      = array(
            'uid'       => $uid
            ,'get_time' => $bettoday
        );
        $result = apiCall(GamePrizegethisApi::COUNT,array($map));
        $r['info']['remainA'] = $maxChange - intval($result['info']);
//今天是否签到
        $map    = array(
            'uid'           => $uid
            ,'sign_in_time' => $bettoday
        );
        $result = apiCall(SigninApi::GET_INFO,array($map));
        if($result['status']){
            $info = $result['info'];
//是否签到
            if($info){
                $r['info']['signin']  = true;
//查询今天剩余免费次数
                $map = array(
                    'uid'        => $uid
                    ,'get_time'  => $bettoday
                    ,'prize_type'=> 0
                );
                $result = apiCall(GamePrizegethisApi::COUNT,array($map));
                if($result['status']){
                    $m = $maxFree - intval($result['info']);
                    $r['info']['remainF'] = $m>0 ? $m:0;
                }else{
                    $r['msg']           = 'GamePrizegethisApi : ERROR';
                }
            }else{
                $r['info']['signin']  = false;
                $r['info']['remainF'] = 0;
            }
            $r['status']        = true;
//查询用户积分
            $map                = array('uid' => $uid);
            $result             = apiCall(MemberApi::GET_INFO,array($map));
            $r['info']['score'] = $result['info']['score'] ? $result['info']['score']:0;
        }else{
            $r['msg']           = 'SigninApi : ERROR';
        }
        $result = apiCall(GameApi::FIND,array(array('id'=>$gid)));
        if($result['status']) $r['info']['game_name'] = $result['info']['name'];
        unset($result);
        // dump($r);exit;
        return $r;
    }
    /**
     * 抽奖主体
     * @param  [int]    $gid[the game id]
     * @return [arr]    [本次抽奖结果]
     */
    protected function doRoll($gid){
        $data = array();
        $arr = array();
        $result = apiCall(GamePrizeApi::FINDALL,array(array('game_id'=>$gid)));
        if(!$result['status'])
            return array('status'=>false,'info'=>null,'msg'=>'GamePrizeApi : ERROR');
        $prizes = $result['info'];
        foreach($prizes as $k=>$v) {
            // $val = intval($v['cnt'])*intval($v['value']);
            $arr[$v['id']] = $v['probability'] * 100;
        }
        $prize_id = $this->getRand($arr); //根据概率获取奖项id
        foreach($prizes as $k=>$v){ //获取前端奖项位置
            if($v['id'] == $prize_id){
                 $prize_site = $k;
                 break;
            }
        }
        $data['prize_name'] = $prizes[$prize_site]['prize_name'];
        $data['prize_num']  = $prizes[$prize_site]['prize_num'];
        $data['prize_type'] = $prizes[$prize_site]['prize_type'];
        $data['prize_site'] = $prize_site;
        $data['prize_id']   = $prize_id;
        return array('status'=>true,'info'=>$data,'msg'=>'');
    }
    /**
     * 获取roll点结果
     * @param  [type] $proArr [description]
     * @return [int]          [0|未中奖,]
     */
    protected function getRand($proArr) {
        $randNum = mt_rand(0, 100); //roll点
        foreach ($proArr as $k => $v) { //概率数组循环
            if ($randNum <= $v )
            {
               return $k;
            }else{
                $randNum -=$v;
            }
        }
        return 0;
    }
    /**
     * 奖品类型
     * 1积分   => 直接发放
     * 2购物券 => 直接发
     * 3商品   => 0.1元加入用户购物车
     * 4其他   => 工作人员联系
     * @return [type] [description]
     */
    public function getPrizeCats(){
        return $this->apiReturnSuc(array(1=>'积分',2=>'购物券',3=>'商品',4=>'其他'));
        // $cat = D('Datatree')->where(array('code'=>'PrizeCat'))->find();
        // return D('Datatree')->where(array('parentid'=>$cat['id']))->select();
    }
}
